const fs = require('fs-extra');
const chalk = require('chalk');
const utils = require('./utils');
const crossSpawn = require('cross-spawn');
const spawn = crossSpawn.sync;
const red = chalk.red;
const green = chalk.green;
const {currentPath} = utils;
// 项目名称
let projectName;
// 项目路径
let projectPath;

// 重写package.json
async function rewriteJson() {
    try {
        const path = currentPath + projectName + '/package.json';
        const isExist = await fs.pathExists(path);
        if (!isExist) {
            return;
        }
        const json = await fs.readJson(path);
        json.name = projectName;
        await fs.writeJson(path, json, {spaces: '\t'});
        console.log(green('格式化 package.json 成功!'));
    } catch (err) {
        console.error(red(err));
    }
}

/**
 * 删除不相关文件
 * @param path
 * @param callback
 * @returns {Promise<void>}
 */
async function unrelatedFileRemove(path = projectPath, callback) {
    try {
        await fs.remove(path + '/.git');
        callback && callback();
        await rewriteJson();
        console.log(green('删除不相关文件成功!'));
        console.log(green('完成!'));
    } catch (err) {
        console.error(red(err));
    }
}

function downloadByGit(projectDir, callback) {
    console.log(green('开始下载模版'));
    const result = spawn(
        'git',
        ['clone', `https://gitee.com/Kuss/React-Template.git`, projectDir],
        {stdio: 'inherit'}
    );
    const error = result.error;
    if (error) {
        console.log(red(error));
        return;
    }
    callback && callback(projectDir);
}

async function create(project, force = false) {
    projectName = project;
    // forceDel = force;
    projectPath = currentPath + projectName;
    try {
        // 检测项目文件夹是否已存在， 若存在，抛出错误
        const exists = await fs.pathExists(projectPath);
        if (exists) {
            if (force) {
                console.log(green('强制删除相同目录'));
                await fs.emptyDir(projectPath);
                downloadByGit(projectPath, unrelatedFileRemove);
            } else {
                console.log(chalk.red('创建失败!此目录中已有相同项目名称!'));
                console.log(chalk.green('你可以使用 -f 选项强制删除该目录并创建工程!'));
            }
            return;
        }
        // 若不存在，直接从git下载
        downloadByGit(projectPath, unrelatedFileRemove);
    } catch (err) {
        console.error(red(err));
    }
}

module.exports = create;